
//
//  HNAccountTool.m
//  HappyNews
//
//  Created by baiping on 16/1/9.
//  Copyright © 2016年 BPWBANP. All rights reserved.
//

#import "HNAccountTool.h"
#import "AppDelegate.h"

@interface HNAccountTool()

@property (nonatomic, strong) NSManagedObjectContext *context;

@end



@implementation HNAccountTool

+ (HNAccountTool *)shareAccountTool{
    
    
    static HNAccountTool *accountTool = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        accountTool = [[HNAccountTool alloc]init];
        
        
    });

    return accountTool;
    
}



- (NSManagedObjectContext *)context{
    
    
    if (!_context) {
        
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
        
    _context = delegate.managedObjectContext;
        
        
    }
    
    return _context;
    
    
}


- (void)saveAccount:(Users *)account{
    
    
    Users *user = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:self.context];
    
    user = account;
   
    [self.context save:nil];
    

    
}

- (BOOL)isExistAccount{
    
    // 创建一个用于查找的请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    // 创建一个表的描述(即代表了那张表)
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Users" inManagedObjectContext:self.context];
    // 设置去拿张表查找
    [fetchRequest setEntity:entity];
   
    // 谓词 可以作为查找的条件, 谓词里面的条件是SQL语句的查找条件
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", account.name];
    // 设置查找的条件
    // [fetchRequest setPredicate:predicate];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
    
    if (fetchedObjects == nil || fetchedObjects.count == 0) {
        
        return NO;
        
    }else{
        
        
        return YES;
    }
    
    
}


- (BOOL)isExistCurrrentAccount{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *lastVersion = [defaults stringForKey:@"name"];
 
    if (lastVersion) {
        
        return YES;
        
    }else{
        
        return NO;
    }

}


@end
